const app = getApp();

import {
  UserModel
} from '../../../models/user.js';

import { 
  config
} from '../../../config/config.js';

const userModel = new UserModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    showLoginDialog: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },
  
  onShow: function() {
    this.setData({
      userInfo: app.globalData.userInfo,
    });
  },

  onUserInfoClick: function() {
    if (wx.getStorageSync('token')) {

    } else {
      this.showLoginDialog();
    }
  },

  showLoginDialog() {
    this.setData({
      showLoginDialog: true
    })
  },

  onCloseLoginDialog () {
    this.setData({
      showLoginDialog: false
    })
  },
  
  onDialogBody () {
    // 阻止冒泡
  },

  onWechatLogin: function(event) {
    if(event.detail.errMsg !== 'getUserInfo:ok'){
      if (event.detail.errMsg === 'getUserInfo:fail auth deny') {
        return;
      }
      wx.showToast({
        title: '微信登录失败',
      })
      return;
    }

    userModel.login().then(res => {
      return userModel.getAuthLoginByWeixin(res, event.detail)
    })
    .then(res => {      
      if (res.errno !== 0) {
        wx.showToast({
          title: '微信登录失败',
        })
        return;
      }

      // 设置用户信息
      this.setData({
        userInfo: res.data.userInfo,
        showLoginDialog: false
      });
      // app.globalData.userInfo = res.data.userInfo;
      // app.globalData.token = res.data.token;
      wx.setStorageSync('userInfo', JSON.stringify(res.data.userInfo));
      wx.setStorageSync('token', res.data.token);
    })
    .catch(err => {
      console.log(err);
    })
  }
})